# @FileName  : bd.py
# @Time      : 2022/1/18 14:45
# @Author    : LuZhaoHui
# @Software  : PyCharm

import self as self
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PIL import Image

from bddata import Ui_MainWindow
from configparser import ConfigParser

import os, sys, xlrd, time

IMG_EXT = (".jpg")
XLS_EXT = (".xls", ".xlsx")

ver = '0.22.3.7'

# 图片信息：段标识(1-0xff)+段类型(1-IMG_XXXX)+段长度(2)+段内容(n)
# 段类型
IMG_MARK = 0xff  # 段标识
IMG_SOI = 0xd8  # 文件头
IMG_APP0 = 0xe0  # 定义交换格式和图像识别信息
IMG_APP1 = 0xe1  #
IMG_APPF = 0xef  #
IMG_DQT = 0xdb  # 定义量化表
IMG_DRI = 0xdd  # 定义重新开始间隔
IMG_SOF0 = 0xc0  # 帧开始
IMG_SOF1 = 0xc1
IMG_DHT = 0xc4  # 定义HUFFMAN表
IMG_SOS = 0xda  # 扫描行开始
IMG_EOI = 0xd9  # 文件尾
IMG_COM = 0xfe  # 注释


def setComboBoxHeight(combo, h):
    combo.setStyleSheet("QAbstractItemView::item{height: %dpx;}" % (h))
    combo.setView(QListView())


def pathJoin(path1, path2):
    return os.path.join(path1, path2).replace('\\', '/')


def getImg0File(file):
    size = [0, 0]
    unit = 0
    density = [0, 0]
    dot = [0, 0]
    with open(file, 'rb') as f:
        l = 64 * 1024
        data = f.read(l)
        i = 0
        while i < l:
            # i += 1
            if data[i] == IMG_MARK:
                i += 1
                continue
            elif data[i] == IMG_APP0:
                # 图像识别信息
                i += 1
                ch = data[i]
                cl = data[i + 1]
                len = ch * 256 + cl
                j = i + 2
                j += 5
                j += 2
                unit = data[j]
                j += 1
                ch = data[j]
                cl = data[j + 1]
                density[0] = ch * 256 + cl
                j += 2
                ch = data[j]
                cl = data[j + 1]
                density[1] = ch * 256 + cl
                j += 2
                dot[0] = data[j]
                j += 1
                dot[1] = data[j]
                i += len
                continue
            elif data[i] == IMG_COM or (data[i] >= IMG_APP1 and data[i] <= IMG_APPF):
                # 图像识别信息
                i += 1
                ch = data[i]
                cl = data[i + 1]
                len = ch * 256 + cl
                i += len
                continue
            elif data[i] == IMG_SOI:
                i += 1
                continue
            elif data[i] == IMG_DQT:
                i += 1
                ch = data[i]
                cl = data[i + 1]
                len = ch * 256 + cl
                i += len
                continue
            elif data[i] == IMG_SOF0:
                # 图像基本信息:段标识(1,FF),段类型(1,C0),段长度(2,8＋组件数量×3)
                i += 3
                # 样本精度(1,8),图片高度(2),图片宽度(2)
                i += 1
                ch = data[i]
                i += 1
                cl = data[i]
                size[1] = ch * 256 + cl
                i += 1
                ch = data[i]
                i += 1
                cl = data[i]
                size[0] = ch * 256 + cl
                # 组件数量(1,1＝灰度图，3＝YCbCr / YIQ,4＝CMYK),（以下每个组件占用３字节）
                break
            else:
                break
    return size + density


def getImgFile(file, isSet):
    try:
        image = Image.open(file)
    except Exception:
        return (0, 0, 0.0, 0.0, 'RGB')
    if 'dpi' in image.info:
        if image.info['dpi'][0] != 300 or image.info['dpi'][1] != 300:
            if isSet:
                image.save(file, dpi=(300, 300))
            else:
                return image.size + (image.info['dpi'][0], image.info['dpi'][1]) + tuple([image.mode])
        return image.size + (300, 300) + tuple([image.mode])
    else:
        if isSet:
            image.save(file, dpi=(300, 300))
            return image.size + (300, 300) + tuple([image.mode])
        else:
            return image.size + (0.0, 0.0) + tuple([image.mode])


def showLabelImage(area, label, name, self):
    img = QImage()
    img.load(name)
    if self:
        w = area.width()
        h = area.height()
        new_img = img.scaled(w, h, Qt.KeepAspectRatio)
        label.setPixmap(QPixmap.fromImage(new_img))
    else:
        label.setPixmap(QPixmap.fromImage(img))


def readXlsx(name):
    data = []
    if os.path.exists(name):
        #     read = openpyxl.load_workbook(name)
        #     sheets = read.get_sheet_names()
        #     sheet = read.get_sheet_by_name(sheets[0])
        #     rows = sheet.rows
        #     for row in rows:
        #         line = [col.value for col in row]
        #         data.append(line)
        read = xlrd.open_workbook(name)
        sheetName = read.sheet_names()
        for s, sname in enumerate(sheetName):
            sheet = read.sheet_by_name(sname)
            # print(sheet.name, sheet.nrows, sheet.ncols)
            for i in range(sheet.nrows):
                row = sheet.row_values(i)
                if len(row[0]) == 0:
                    continue
                row.append(s)
                row.append(i)
                # print(row)
                data.append(row)
    return data


class MyParser(ConfigParser):
    "Inherit from built-in class: ConfigParser"

    def optionxform(self, optionstr):
        "Rewrite without lower()"
        return optionstr


class bdConf():
    def __init__(self, file):
        self.initVar()
        self.config = MyParser()
        self.name = file
        self.readConf()

    def initVar(self):
        # 设计配置
        self.varConf = {'CurPath': '',
                        'WindowMax': 0}

    def getConfig(self, section, key):
        return self.config.get(section, key)

    def readConf(self):
        self.config.read(self.name, 'utf-8')
        # [CONF]
        for k in self.varConf:
            str = self.getConfig('CONF', k)
            if isinstance(self.varConf[k], int):
                self.varConf[k] = int(str)
            else:
                self.varConf[k] = str

    def writeConf(self):
        for k in self.varConf:
            self.config.set('CONF', k, str(self.varConf[k]))
        with open(self.name, 'w', encoding='utf-8') as f:
            self.config.write(f)


class ListDataCheck(QThread):
    update_item = pyqtSignal(list)

    def __init__(self, list):
        super().__init__()
        self.list = list

    def run(self):
        nums = len(self.list)
        for i in range(nums):
            self.update_item.emit([i, nums])
            time.sleep(0.15)
        self.update_item.emit([0])


class ReadAllList(QThread):
    update_item = pyqtSignal(list)

    def __init__(self, dirList, isAll, isSet, typeList):
        super().__init__()
        self.list = dirList
        self.isAll = isAll
        self.isSet = isSet
        self.typeList = typeList
        self.typeMaxIndex = 0
        self.typeMaxNo = 0

    def getFileTypeIndex(self, type):
        if type[1] > '0':
            for i in range(len(self.typeList)):
                if type[0] in '49':
                    if self.typeList[i][1] == '%s-%s' % (type[0], type[1]):
                        return i, int(type[2]), int(type[3])
                else:
                    if self.typeList[i][1] == type[0]:
                        return i, int(type[1]), int(type[2])
        return 0, 0, int(type[0])

    def run(self):
        for allDir in self.list:
            dirName = allDir
            dir1 = os.path.basename(allDir)
            if self.isAll:
                if os.path.isdir(dirName):
                    fs = os.listdir(dirName)
                    for f in fs:
                        name = pathJoin(dirName, f)
                        if os.path.isdir(name):
                            dirName = name
                            break
            self.update_item.emit([os.path.basename(dirName)])
            files = os.listdir(dirName)
            for f in files:
                name = pathJoin(dirName, f)
                name1 = os.path.splitext(f)[0]
                isFile = os.path.isfile(name)
                ext = os.path.splitext(name)
                f1 = f
                f2 = f
                if isFile and ext[1] in IMG_EXT:
                    isSet = self.isAll and self.isSet
                    size = getImgFile(name, isSet)
                    if self.isAll:
                        if size[2] == 300 and size[3] == 300:
                            continue
                        f2 = pathJoin(dir1, os.path.basename(dirName))
                    ts = ''
                    if not self.isAll:
                        ts = name1.split('-')
                        while len(ts) < 3:
                            ts.append('0')
                        t1, t2, t3 = self.getFileTypeIndex(ts)
                        ts.append(-1 if t1 == 0 and t2 == 0 else t1)
                        if self.typeMaxIndex < ts[-1]:
                            self.typeMaxIndex = ts[-1]
                            self.typeMaxNo = 1
                        if self.typeMaxIndex == ts[-1]:
                            if self.typeMaxNo < t2:
                                self.typeMaxNo = t2
                    flist = [f1, f2,
                             size[0], size[1],
                             size[2], size[3],
                             ts, ts
                             ]
                    self.update_item.emit(flist)
        self.update_item.emit([self.typeMaxIndex, self.typeMaxNo])


class bddataRun(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(bddataRun, self).__init__(parent)
        self.setupUi(self)
        self.init()

    def init(self):
        self.config = bdConf('bd.ini')
        if self.config.varConf['WindowMax'] > 0:
            self.showMaximized()
        self.isAll = False
        self.setWindowTitle('档案目录工具软件-  [Ver ' + ver + ']')
        setComboBoxHeight(self.comboBoxCurFileType, 16)
        self.pushButtonCurDir.clicked.connect(self.choiceCurDir)
        self.pushButtonCurDirScan.clicked.connect(self.scanCurDir)
        self.pushButtonFileRename.clicked.connect(self.renameFiles)
        self.pushButtonFileRecover.clicked.connect(self.recoverFile)
        self.pushButtonUp.clicked.connect(self.listUp)
        self.pushButtonDown.clicked.connect(self.listDown)
        self.pushButtonPageUp.clicked.connect(self.listPageUp)
        self.pushButtonPageDown.clicked.connect(self.listPageDown)
        self.pushButtonDataCheck.clicked.connect(self.listDataCheck)
        self.pushButtonRotate.clicked.connect(self.fileRotate)
        self.comboBoxCurFileType.currentIndexChanged.connect(self.selectFileType)
        self.checkBoxAllScan.clicked.connect(self.setAll)
        self.varCurDir = ''
        self.varCurAllDir = []
        self.varCurDirScanPath = ''
        self.varCurDirExcel = ''
        self.varCurDataList = []
        self.varCurName = ''
        self.varCurDirIndex = -1
        self.varCurTypeIndex = 0
        self.varCurTypeMaxIndex = 0
        self.varCurTypeMaxNo = 0
        self.varCurType = ''
        self.varCurTypeList = []
        for i in range(self.comboBoxCurFileType.count()):
            self.varCurTypeList.append(self.comboBoxCurFileType.itemText(i).split(' '))
        self.varCurIdcard = ''
        self.varCurDirFileList = []
        self.listWidgetCurFile.itemClicked.connect(self.choiceCurFile)
        self.listWidgetCurFile.currentRowChanged.connect(self.selectCurFile)
        self.readCurPath(self.config.varConf['CurPath'])
        self.listDataCheckThread = None
        self.errList = []
        self.readAllListThread = None

    def setAll(self):
        self.isAll = self.checkBoxAllScan.isChecked()

    def keyPressEvent(self, event):
        key = event.key()
        # print("press: " + str(key))
        if key == Qt.Key_Enter:
            # print("press: enter")
            self.renameFiles()
        elif key == Qt.Key_Up:
            self.listUp()
        elif key == Qt.Key_Down:
            self.listDown()
        elif key == Qt.Key_Left or key == Qt.Key_PageUp:
            self.listPageUp()
        elif key == Qt.Key_Right or key == Qt.Key_PageDown:
            self.listPageDown()

    def selectFileType(self):
        index = self.comboBoxCurFileType.currentIndex()
        if index != self.varCurTypeIndex:
            self.varCurTypeIndex = index
            self.varCurType = self.comboBoxCurFileType.currentText()
            self.spinBoxCurFileNo.setValue(1)
            self.spinBoxCurFileNums.setValue(1)

    def getFileTypeIndex(self, type):
        if type[1] > '0':
            for i in range(len(self.varCurTypeList)):
                if type[0] in '49':
                    if self.varCurTypeList[i][1] == '%s-%s' % (type[0], type[1]):
                        return i, int(type[2]), int(type[3])
                else:
                    if self.varCurTypeList[i][1] == type[0]:
                        return i, int(type[1]), int(type[2])
        return 0, 0, int(type[0])

    # 数据核查
    def showDataCheck(self, list):
        if len(list) == 2:
            self.selectCurFile(list[0])

    def listDataCheck(self):
        self.textEditCheckResult.clear()
        self.errList = []
        self.listDataCheckThread = ListDataCheck(self.varCurDirFileList)
        self.listDataCheckThread.update_item.connect(self.showDataCheck)
        self.listDataCheckThread.start()

    def dataCheck(self):
        # 读取xls数据
        self.textEditCheckResult.clear()
        self.errList = []
        xlsx = readXlsx(self.varCurDirExcel)
        # 核查数据
        data = []
        type = -1
        for d in xlsx:
            isOk = False
            tl1 = [t[0] for t in self.varCurTypeList]
            tl2 = [t[1] for t in self.varCurTypeList]
            try:
                i = tl1.index(d[0])
            except ValueError:
                i = -1
            if i >= 0:
                type = i
            else:
                if d[0].isdigit():
                    isOk = True
                    no = int(d[0])
                    if d[10] == 1 and d[11] >= 21 and type == 1:
                        type += 1
                    if d[10] == 1 and d[11] >= 93 and type == 10:
                        type += 1
                    if d[10] == 1 and d[11] >= 111 and type == 11:
                        type += 1
                else:
                    try:
                        i = tl2.index(d[0])
                    except ValueError:
                        i = -1
                    if i >= 0:
                        type = i
            if not isOk:
                continue
            data.append([type, self.varCurTypeList[type][1]] + d)

            # m = re.match('[\d-]+', d[0])
            # if m != None and m.group() == d[0]:
            #     isOk = True
        data.sort(key=lambda x: x[0])
        self.varCurDataList = []
        self.listWidgetCurData.clear()
        for d in data:
            self.varCurDataList.append(d)
            item = QListWidgetItem(self.getDataList(d))
            self.listWidgetCurData.addItem(item)

    def getDataList(self, data):
        itemText = '%s-%s\t%-36s\t%s-%s-%s\t%d' % (data[1], data[2],
                                                   data[3],
                                                   data[4], data[5], data[6],
                                                   int(data[7]))
        return itemText

    def getFileName(self, index):
        return os.path.splitext(self.varCurDirFileList[index][0])[0], \
               self.varCurDirFileList[index][6][-1] >= 0, \
               self.varCurDirFileList[index][6]

    # 选择当前文件
    def selectCurFile(self, index):
        if self.isAll:
            return
        if index < 0:
            return
        self.varCurDirIndex = index
        # 显示图片
        self.listFlush()

    # 显示当前文件
    def choiceCurFile(self):
        try:
            index = self.listWidgetCurFile.selectedIndexes()
        except Exception:
            return
        if index[0].row() == self.varCurDirIndex:
            return
        self.varCurDirIndex = index[0].row()
        # 显示图片
        self.listFlush()

    def fileRotate(self):
        name = pathJoin(self.varCurDirScanPath, self.varCurDirFileList[self.varCurDirIndex][0])
        image = Image.open(name)
        image = image.transpose(Image.ROTATE_90)
        image.save(name, dpi=(300, 300))

        showLabelImage(self.scrollArea, self.labelCurImage, name, True)

    def listImage(self):
        if self.isAll:
            name = pathJoin(self.varCurDir, self.varCurDirFileList[self.varCurDirIndex][1])
            name = pathJoin(name, self.varCurDirFileList[self.varCurDirIndex][0])
        else:
            name = pathJoin(self.varCurDirScanPath, self.varCurDirFileList[self.varCurDirIndex][0])
        showLabelImage(self.scrollArea, self.labelCurImage, name, True)

    def listAllFlush(self):
        if not self.isAll:
            self.varCurDirFileList.sort(key=lambda x: (int(x[6][1] if x[6][1] == '0' else x[6][0]),
                                                       int(x[6][0] if x[6][1] == '0' else x[6][1]),
                                                       int(x[6][2])))
        self.listWidgetCurFile.clear()
        for flist in self.varCurDirFileList:
            item = QListWidgetItem(self.getFileList(flist))
            self.listWidgetCurFile.addItem(item)

    def errAdd(self, index):
        c = self.errList.count(index)
        if c > 0:
            return True
        self.errList.append(index)
        return False

    def listFlush(self):
        # item = QListWidgetItem(self.getFileList(self.varCurDirFileList[self.varCurDirIndex]))
        # self.listWidgetCurFile.setCurrentItem(item)
        self.listWidgetCurFile.setFocus()
        self.listWidgetCurFile.setCurrentRow(self.varCurDirIndex)
        self.listImage()
        if self.isAll:
            return
        # 判断名称是否更名
        name, isOk, type = self.getFileName(self.varCurDirIndex)
        self.lineEditCurDirFile.setText('%s->%d %s' % (name, self.varCurDirIndex, '已更名' if isOk else '未更名'))
        t1, t2, t3 = self.getFileTypeIndex(type)
        if type[-1] >= 0:
            self.comboBoxCurFileType.setCurrentIndex(t1)
            self.spinBoxCurFileNo.setValue(t2)
            self.spinBoxCurFileNums.setValue(t3)
            page = 0
            for i, d in enumerate(self.varCurDataList):
                if t1 == d[0] and t2 == int(d[2]):
                    page = int(d[7])
                    self.listWidgetCurData.setCurrentRow(i)
                    break
            err = ''
            if page == 0 and self.errAdd(self.varCurDirIndex):
                err += '%s 图片名[%s]索引[%d]无此类型\n' % (self.varCurTypeList[type[-1]], name, t3)
            if t3 == 1 and page > 0:
                c = 1
                for i in range(page):
                    if (self.varCurDirIndex + 1 + i) >= len(self.varCurDirFileList):
                        break
                    name, isOk, t = self.getFileName(self.varCurDirIndex + 1 + i)
                    if len(type) == 4:
                        if t[0] == type[0] and t[1] == type[1]:
                            c += 1
                    else:
                        if t[0] == type[0] and t[1] == type[1] and t[2] == type[2]:
                            c += 1
                if c != page and self.errAdd(self.varCurDirIndex):
                    err += '%s 图片数[%d]与页数[%d]不符\n' % (self.varCurTypeList[type[-1]], c, page)
            if page > 0 and t3 > page and self.errAdd(self.varCurDirIndex):
                err += '%s 图片名索引[%d]大于页数[%d]\n' % (self.varCurTypeList[type[-1]], t3, page)
            if err != '':
                self.textEditCheckResult.append(err)
        else:
            self.spinBoxCurFileNums.setValue(self.varCurDirIndex + 1)

    def getIndex(self, c):
        if self.varCurDirIndex < 0 or len(self.varCurDirFileList) == 0:
            return False
        #
        old = self.varCurDirIndex
        index = self.varCurDirIndex + c
        if c > 0:
            if index < len(self.varCurDirFileList):
                self.varCurDirIndex = index
            else:
                self.varCurDirIndex = len(self.varCurDirFileList) - 1
        else:
            if index >= 0:
                self.varCurDirIndex = index
            else:
                self.varCurDirIndex = 0
        return self.varCurDirIndex != old

    def listUp(self):
        if self.getIndex(-1):
            self.listFlush()

    def listPageUp(self):
        if self.getIndex(-10):
            self.listFlush()

    def listDown(self):
        if self.getIndex(1):
            self.listFlush()

    def listPageDown(self):
        if self.getIndex(10):
            self.listFlush()

    def getFileList(self, file):
        itemText = '%-24s%-24s\t%04dx%04d\t%03d-%03d' % (file[0],
                                                         file[1],
                                                         file[2],
                                                         file[3],
                                                         int(file[4]),
                                                         int(file[5]))
        return itemText

    def getCurDirFiles(self):
        # self.comboBoxCurFileType.setCurrentIndex(0)
        # self.spinBoxCurFileNums.setValue(0)
        self.lineEditCurDir.setText("%s-[%d]" % (self.varCurDir, len(self.varCurDirFileList)))

    # 选择当前目录
    def readCurPath(self, path):
        if os.path.exists(path):
            if self.isAll:
                self.varCurDir = ''
            if self.varCurDir != path:
                # self.lineEditCurDir.setText(path)
                self.varCurDir = path
                dir = os.path.basename(self.varCurDir)
                self.varCurDirScanPath = ''
                self.varCurDirExcel = ''
                self.varCurAllDir = []
                files = os.listdir(self.varCurDir)
                for f in files:
                    name = pathJoin(self.varCurDir, f)
                    if self.isAll:
                        if os.path.isdir(name):
                            self.varCurAllDir.append(name)
                    else:
                        if os.path.isfile(name) and os.path.splitext(name)[1] in XLS_EXT:
                            self.varCurDirExcel = name
                        if os.path.isdir(name) and dir == f[:len(dir)]:
                            self.varCurDirScanPath = name
                self.scanCurDir()
                self.getCurDirFiles()
                self.config.varConf['CurPath'] = self.varCurDir
                self.config.writeConf()

    def choiceCurDir(self):
        path = QFileDialog.getExistingDirectory(self, "选择档案目录", self.varCurDir)
        self.readCurPath(path)

    def readListShow(self, list):
        if len(list) == 1:
            self.lineEditCurDir.setText("%s-[%d]" % (list[0], len(self.varCurDirFileList)))
        elif len(list) != 2:
            self.varCurDirFileList.append(list)
        else:
            self.varCurTypeMaxIndex = list[0]
            self.varCurTypeMaxNo = list[1]
            self.lineEditCurDir.setText("%s-[%d]" % (self.varCurDir, len(self.varCurDirFileList)))
            if len(self.varCurDirFileList):
                self.listAllFlush()
                if not self.isAll:
                    self.dataCheck()
                    self.comboBoxCurFileType.setCurrentIndex(self.varCurTypeMaxIndex)
                    self.spinBoxCurFileNo.setValue(self.varCurTypeMaxNo + 1)
                    self.varCurDirIndex = 0
                    self.listFlush()

    # 扫描当前目录
    def scanCurDir(self):
        if not self.isAll:
            if self.varCurDirScanPath.isspace():
                return
            if not os.path.exists(self.varCurDirScanPath):
                return
            self.varCurAllDir.clear()
            self.varCurAllDir.append(self.varCurDirScanPath)
        self.varCurTypeMaxIndex = 0
        self.varCurDirFileList = []
        self.listWidgetCurFile.clear()
        self.listWidgetCurData.clear()
        self.textEditCheckResult.setText('')
        self.labelCurImage.clear()

        isSet = self.isAll and self.checkBox300List.isChecked()
        self.readAllListThread = ReadAllList(self.varCurAllDir, self.isAll, isSet, self.varCurTypeList)
        self.readAllListThread.update_item.connect(self.readListShow)
        self.readAllListThread.start()

    # 恢复名称
    def recoverFile(self):
        if self.varCurDirIndex < 0:
            return
        if len(self.varCurDirFileList) == 0:
            return
        oldName = pathJoin(self.varCurDirScanPath, self.varCurDirFileList[self.varCurDirIndex][0])
        fileName = pathJoin(self.varCurDirScanPath, self.varCurDirFileList[self.varCurDirIndex][1])
        os.rename(oldName, fileName)
        self.varCurDirFileList[self.varCurDirIndex][0] = self.varCurDirFileList[self.varCurDirIndex][1]
        self.varCurDirFileList[self.varCurDirIndex][6] = self.varCurDirFileList[self.varCurDirIndex][7]
        self.listAllFlush()

    # 批量改名
    def renameFiles(self):
        if self.varCurDirIndex < 0:
            return
        if len(self.varCurDirFileList) == 0:
            return
        # rename
        pageNums = self.spinBoxCurFileNums.value()
        pageNo = self.spinBoxCurFileNo.value()
        n = 0
        while True:
            index = self.varCurDirIndex - n
            name, isOk, type = self.getFileName(index)
            if isOk:
                break
            # 更名
            name = '%s-%d-%03d' % (self.varCurTypeList[self.varCurTypeIndex][1],
                                   pageNo,
                                   pageNums)
            ext = os.path.splitext(self.varCurDirFileList[index][0])[1]
            oldName = pathJoin(self.varCurDirScanPath, self.varCurDirFileList[index][0])
            fileName = pathJoin(self.varCurDirScanPath, name + ext)
            try:
                os.rename(oldName, fileName)
            except Exception:
                break
            # 更新列表
            self.varCurDirFileList[index][0] = name + ext
            ts = name.split('-')
            t1, t2, t3 = self.getFileTypeIndex(ts)
            ts.append(-1 if t1 == 0 and t2 == 0 else t1)
            if self.varCurTypeMaxIndex < ts[-1]:
                self.varCurTypeMaxIndex = ts[-1]
                self.varCurTypeMaxNo = 1
            if self.varCurTypeMaxIndex == ts[-1]:
                if self.varCurTypeMaxNo < t2:
                    self.varCurTypeMaxNo = t2
            self.varCurDirFileList[index][6] = ts
            n += 1
            if index == 0:
                break
            pageNums -= 1
        if n > 0:
            self.listAllFlush()
            self.spinBoxCurFileNo.setValue(self.varCurTypeMaxNo + 1)
            self.varCurDirIndex = 0
            self.listFlush()


if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = bddataRun()
    main.show()

    sys.exit(app.exec_())
